package com.rookieCi.qrcodefile.sync;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.PointF;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.dlazaro66.qrcodereaderview.QRCodeReaderView;
import com.google.gson.Gson;
import com.rookieCi.qrcodefile.BuildConfig;
import com.rookieCi.qrcodefile.R;
import com.rookieCi.qrcodefile.mode.CodeMode;
import com.rookieCi.qrcodefile.mode.NoteMode;
import com.rookieCi.qrcodefile.utils.CodeUtils;
import com.rookieCi.qrcodefile.utils.Logger;
import com.rookieCi.qrcodefile.utils.PrivateFileUtils;
import com.xcc.myzxing.PointsOverlayView;

import butterknife.BindView;
import butterknife.ButterKnife;

public class SendFileActivity extends AppCompatActivity implements QRCodeReaderView.OnQRCodeReadListener, OnFileContactInterface {
    public static final int MY_PERMISSION_REQUEST_CAMERA = 0xFF00;
    @BindView(R.id.image)
    public ImageView image;
    @BindView(R.id.layoutPreview)
    public ViewGroup layoutPreview;
    private SendFileContact fileContact;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send_file);
        ButterKnife.bind(this);

        Intent intent = getIntent();
        fileContact = new SendFileContact(intent, this);

        image.postDelayed(this::initSowCode, 100);

        setTitle("开始发送");
    }

    private void initSowCode() {
        if (requestFilePermissions) return;
        showCode();
        openCamera();
        if (fileContact.getSendType() == 0) {
            if (fileContact.isOpenFile()) return;
            new AlertDialog.Builder(SendFileActivity.this)
                    .setTitle("呵呵哒")
                    .setMessage("加载文件失败")
                    .setPositiveButton("知道了", null)
                    .show();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (qrCodeReaderView != null) {
            qrCodeReaderView.startCamera();
        }
    }

    @Override
    protected void onPause() {
        if (qrCodeReaderView != null) {
            qrCodeReaderView.stopCamera();
        }
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        fileContact.onDestroy();
        PrivateFileUtils.deleteAllEnd(this, ".xcczip");//删除文件
        super.onDestroy();
    }

    private void showCode() {
        CodeMode codeMode = new CodeMode(fileContact);
        String text = codeMode.getJsonString();
        try {
            Bitmap bitmap = new CodeUtils()
                    .setEnd(codeMode.idx == -1)
                    .Create2DCode(text);
            image.setImageBitmap(bitmap);
        } catch (Exception e) {
            if (BuildConfig.DEBUG) e.printStackTrace();
        }
    }

    private void openCamera() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
            initQRCodeReaderView();
        } else {
            requestCameraPermission();
        }
    }

    private QRCodeReaderView qrCodeReaderView;
    private PointsOverlayView pointsOverlayView;

    private void initQRCodeReaderView() {
        View content = getLayoutInflater().inflate(R.layout.layout_send_content_decoder, layoutPreview, true);

        qrCodeReaderView = content.findViewById(R.id.qrdecoderview);
        pointsOverlayView = content.findViewById(R.id.points_overlay_view);

        qrCodeReaderView.setAutofocusInterval(2000L);
        qrCodeReaderView.setOnQRCodeReadListener(this);
        //qrCodeReaderView.setBackCamera();//后置摄像头
        qrCodeReaderView.setFrontCamera();
        qrCodeReaderView.startCamera();
    }

    private void requestCameraPermission() {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
            AlertDialog dialog = new AlertDialog.Builder(this).setTitle(R.string.cameraRequired)
                    .setNegativeButton(R.string.quxiao, null)
                    .setPositiveButton(R.string.queding, (dialog1, which) ->
                            ActivityCompat.requestPermissions(SendFileActivity.this
                                    , new String[]{Manifest.permission.CAMERA}, MY_PERMISSION_REQUEST_CAMERA))
                    .create();
            dialog.show();
        } else {
            Toast.makeText(this, R.string.myqx_qdksxtqx, Toast.LENGTH_SHORT).show();
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, MY_PERMISSION_REQUEST_CAMERA);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == MY_PERMISSION_REQUEST_CAMERA) {
            if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                initQRCodeReaderView();
            } else {
                Toast.makeText(this, R.string.sxtqxbjj, Toast.LENGTH_SHORT).show();
            }
        } else if (requestCode == 0xFF01) {
            if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                requestFilePermissions = false;
                fileContact.openFile();
                initSowCode();
            } else {
                Toast.makeText(this, "请求不到权限", Toast.LENGTH_SHORT).show();
            }
        } else super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    private boolean requestFilePermissions;

    @Override
    public boolean checkFilePermissions() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            requestFilePermissions = true;
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0xFF01);
            return false;
        } else {
            //fileContact.openFile();
            return true;
        }
    }

    @Override
    public void onQRCodeRead(String text, PointF[] points) {
        if (requestFilePermissions) return;
        if (isDestroyed() || isFinishing()) return;
        pointsOverlayView.setPoints(points);
        Logger.out("扫码结果:" + text);
        //得是个JSON
        try {
            NoteMode noteMode = new Gson().fromJson(text, NoteMode.class);
            Integer index = noteMode.idx;
            Integer no = noteMode.no;
            if (no == null) return;//没有编号不管
            if (index == null || index < 0) return;//结束的不管
            if (no != fileContact.getNo()) return;//编号不同不管
            //显示下一个
            int codeInt = fileContact.getCodeInt();
            if (codeInt == index) {
                fileContact.moveNext();
                showCode();
            }
        } catch (Exception e) {
            if (BuildConfig.DEBUG) e.printStackTrace();
        }
    }
}
